package com.yctan.single;


import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 接收请求
 * @author 谭永超
 */
public class Acceptor implements Runnable {

    private final ServerSocketChannel ssc;
    private final Selector selector;

    public Acceptor(Selector selector, ServerSocketChannel ssc) {
        this.ssc=ssc;
        this.selector=selector;
    }

    @Override
    public void run() {
        try {
            // 等待连接请求
            System.out.println(Thread.currentThread().getName()+"等待请求");
            SocketChannel sc= ssc.accept();
            System.out.println(Thread.currentThread().getName()+sc.socket().getRemoteSocketAddress().toString() + "连接");

            if(sc!=null) {
                // 设置为非阻塞
                sc.configureBlocking(false);
                // SocketChannel向selector组成一个可读事件，然后返回指向改通道的key
                // 注意该处是注册到socketChannel
                SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
                // 是的阻塞的selector 返回操作
                selector.wakeup();
                // 給定key一個附加的TCP处理请求对象
                sk.attach(new TCPHandler(sk, sc));
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}
